﻿namespace ApiTemplate.WebApi.Filter
{
    /// <summary>
    /// 工作单元
    /// </summary>
    public class TransactionFilter : IActionFilter
    {
        private readonly ISqlSugarClient sqlClient;

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="db"></param>
        public TransactionFilter(ISqlSugarClient db)
        {
            sqlClient = db;
        }

        /// <summary>
        /// 开始执行，创建数据库事务
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            sqlClient.Ado.BeginTran();
        }

        /// <summary>
        /// 请求完成，提交事务
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception == null)
            {
                sqlClient.Ado.CommitTran();
            }
            else
            {
                sqlClient.Ado.RollbackTran();
            }
        }
    }
}
